package com.bj.zspace.bytebuddy.bbtest;

import com.bj.zspace.bytebuddy.normal_test.Service;
import net.bytebuddy.ByteBuddy;
import net.bytebuddy.dynamic.DynamicType;
import net.bytebuddy.implementation.FixedValue;
import net.bytebuddy.matcher.ElementMatchers;

import java.io.File;

/**
 * 动态增强的方式
 *  1.sub class
 *  2.rebase: 变基, 原方法保留
 *  3.redefine: 原方法不保留
 *
 */
public class DynamicEnhanceClass {

    public static void main(String[] args) throws Exception {
        String path = Thread.currentThread().getContextClassLoader().getResource("").getPath();
        DynamicType.Unloaded<Service> unloaded = new ByteBuddy()
            .rebase(Service.class).name("a.b.SubService")
            .method(ElementMatchers.named("selectUser").and(ElementMatchers.returns(String.class)))
            .intercept(FixedValue.value("bytebuddy: instance method"))
            .make();

        unloaded.saveIn(new File(path));

        /*Class<? extends Service> loaded = unloaded.load(InstanceMethodClass.class.getClassLoader()).getLoaded();
        Service service = (Service)loaded.getDeclaredConstructors()[0].newInstance();
        System.out.println(service.toString());*/


    }

}
